package com.lecoboy.highconcurrency.concurrent_tools;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CycliBarrier高级功测试类
 */
public class CycliBarrierTest2 {
    //当线程达到屏障后 优先执行 A线程
    static CyclicBarrier c = new CyclicBarrier(2, new A());
    //通过计数器测试reset方法
    static AtomicInteger ai = new AtomicInteger(0);


    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (ai.get() == 0) {
                        ai.getAndIncrement();
                        Thread.currentThread().wait();
                        //throw new NullPointerException("空指针哦");
                    }
                    System.out.println("1就位");
                    c.await();
                } catch (Exception e) {
                }
            }
        }).start();

        try {
            System.out.println("2就位");
            c.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("waiting线程数："+c.getNumberWaiting());
        c.reset();

        System.out.println("完成");
    }

    static class A implements Runnable {
        @Override
        public void run() {
            System.out.println(3);
        }
    }
}
